package com.dzsw.netty.wspb;


import com.dzsw.netty.wspb.adapter.IdleStateTrigger;
import com.dzsw.netty.wspb.adapter.WebSocketHandshakeTrigger;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolConfig;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;


public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        init(pipeline);
    }

    public void init(ChannelPipeline pipeline) {
        pipeline.addLast("log", new LoggingHandler(LogLevel.INFO));
        pipeline.addLast("idleStateHandler", new IdleStateHandler(30, 30, 0, TimeUnit.SECONDS));
        pipeline.addLast("idleStateTrigger", IdleStateTrigger.INSTANCE);

        pipeline.addLast("http-codec", new HttpServerCodec());
        pipeline.addLast("aggregator", new HttpObjectAggregator(Integer.MAX_VALUE));
        pipeline.addLast("http-chunked", new ChunkedWriteHandler());

        WebSocketServerProtocolConfig wsConfig = WebSocketServerProtocolConfig.newBuilder()
                .websocketPath("/test")
                .maxFramePayloadLength(Integer.MAX_VALUE)
                .checkStartsWith(true).build();
        pipeline.addLast("webSocketHandler", new WebSocketServerProtocolHandler(wsConfig));
        pipeline.addLast("handshakeTrigger", WebSocketHandshakeTrigger.INSTANCE);
    }

    public void init0(ChannelPipeline pipeline) {
        //websocket协议本身是基于http协议的，所以这边也要使用http解编码器
        pipeline.addLast(new HttpServerCodec());
        //以块的方式来写的处理器
        pipeline.addLast(new ChunkedWriteHandler());
        //netty是基于分段请求的，HttpObjectAggregator的作用是将请求分段再聚合,参数是聚合字节的最大长度
        pipeline.addLast(new HttpObjectAggregator(8192));

        //ws://server:port/context_path
        //ws://localhost:9999/ws
        //参数指的是contex_path
        WebSocketServerProtocolConfig wsConfig = WebSocketServerProtocolConfig.newBuilder()
                .websocketPath("/test")
                .maxFramePayloadLength(Integer.MAX_VALUE)
                .checkStartsWith(true)
                .build();
        pipeline.addLast(new WebSocketServerProtocolHandler(wsConfig));
//        pipeline.addLast(new PingPongHandler());
        pipeline.addLast(WebSocketHandshakeTrigger.INSTANCE);
        //websocket定义了传递数据的6中frame类型
//        pipeline.addLast(new TextWebSocketFrameHandler());
    }
}
